<template>
    <el-container>
        <el-aside v-loading="dictTreeLoading" width="400px">
            <el-container>
                <el-header>
                    <el-input v-model="dicFilterText" clearable placeholder="输入关键字进行过滤"></el-input>
                    <el-button icon="el-icon-refresh" type="primary" @click="onRefreshDictTree()" style="margin-left: 5px"/>
                </el-header>
                <el-main class="kt-main" style="padding: 0;">
                    <el-tree ref="dictTreeRef" :data="dicList" :expand-on-click-node="true" :filter-node-method="dicFilterNode" :highlight-current="true"
                             node-key="combinationId" class="menu"
                             @node-click="onDictNodeClick">
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span class="label">{{ data.fieldDesc }}（{{ data.fieldName }}）</span>
                                <span class="code">{{ data.tableName }}</span>
								                <span class="do">
                                    <el-button v-auth="'dict:update'" circle link @click.stop="onDictTreeEdit(data)"/>
                                    <el-button v-auth="'dict:delete'" circle link @click.stop="onDictTreeDelete(data)"/>
								                </span>
							              </span>
                        </template>
                    </el-tree>
                </el-main>
                <el-footer style="height:42px;border: 1px dashed var(--el-border-color)">
                    <el-button v-auth="'dict:add'" icon="el-icon-plus" style="width: 100%;"  link @click="onDictTreeEdit()">字典分类</el-button>
                </el-footer>
            </el-container>
        </el-aside>
        <main-page>
            <data-table ref="tableRef" :data="dicts" :pagination="false" primary-key="dictId" v-loading="dictLoading">
                <template #button>
                    <el-button @click="onDictNodeClick()">
                        <template #icon>
                            <svg-icon icon="icon-refresh"/>
                        </template>
                        刷新
                    </el-button>
                    <el-button v-auth="'dict:add'" @click="onCreate()"/>
                </template>
                <template #default>
                    <el-table-column label="名称" prop="description" header-align="center" min-width="180">
                        <template #default="scope">
                            <el-input v-if="scope.row.dictId === currentEditRow?.dictId" v-model="scope.row.description" placeholder="名称"/>
                            <span v-else>{{ scope.row.description }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="键值" prop="value" header-align="center" min-width="180">
                        <template #default="scope">
                            <el-input v-if="scope.row.dictId === currentEditRow?.dictId" v-model="scope.row.value" placeholder="键值"/>
                            <span v-else>{{ scope.row.value }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="status" align="center" width="100">
                        <template #default="scope">
                            <el-switch v-if="scope.row.dictId === currentEditRow?.dictId" v-model="scope.row.status"
                                       :active-value="1" :inactive-value="0" active-text="启" inactive-text="禁" inline-prompt
                                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                            <span v-else>{{scope.row.status === 1? '正常':'禁用'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" prop="order" header-align="center" align="right" width="180">
                        <template #default="scope">
                            <el-input-number v-if="scope.row.dictId === currentEditRow?.dictId" v-model="scope.row.order" placeholder="排序" :min="0"/>
                            <span v-else>{{ scope.row.order }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center"  width="270">
                        <template #default="scope">
                            <el-button v-if="scope.row.dictId !== currentEditRow?.dictId" v-auth="'dict:update'" type="primary" link @click="onEdit(scope.row, true)"/>
                            <el-button v-else v-auth="'dict:update'" type="primary"  link @click="onEdit(scope.row, false)">
                                <template #icon>
                                    <svg-icon icon="icon-save"/>
                                </template>
                                保存
                            </el-button>
                            <el-button v-auth="'dict:delete'" type="danger" link @click="onDelete(scope.row)"/>
                        </template>
                    </el-table-column>
                </template>
            </data-table>
        </main-page>
    </el-container>
    <edit  ref="editRef"/>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import Edit from './edit.vue'
import DataTable from '@/components/data-table/index.vue'
import {service} from '@/utils'


const dictTreeRef = ref()
const editRef = ref<InstanceType<typeof Edit>>()
const tableRef = ref<InstanceType<typeof DataTable>>()

const dictTreeLoading = ref(false)
const dicList = ref<Array<any>>([])

const dictLoading = ref(false)
const dicts = ref([])
const currentEditRow = ref();
const dicItemParams = ref({
    tableName: undefined,
    fieldName: undefined,
    fieldDesc: undefined
})

//加载树数据
const onRefreshDictTree = (combinationId?: string) => {
    dictTreeLoading.value = true;
    service.get('/dict/tree').then(({code, data}) => {
        if (code === 200) {
            dicList.value = data.rows;
            //获取第一个节点,设置选中 & 加载明细列表
            nextTick(() => {
                dictTreeRef.value.setCurrentKey(combinationId || dicList?.value[0]?.['combinationId']);
                onDictNodeClick()
            })
        }
    }).finally(() => dictTreeLoading.value = false)
}

//树过滤
const dicFilterText = ref('')
const dicFilterNode = (value: any, data: any) => {
    if (!value) return true;
    const targetText = data.fieldName + data.fieldDesc + data.tableName;
    return targetText.indexOf(value) !== -1;
}
watch(dicFilterText, (val) =>  dictTreeRef.value.filter(val))


//编辑树
const onDictTreeEdit = (data?: any) => {
    editRef.value?.open({
        data: data,
        type: data? 'put':'post',
        confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
            service[operate]('/dict/tree', form).then(({code}) => {
                if (code === 200) {
                    onRefreshDictTree(form.tableName + "_" + form.fieldName);
                }
                resolve(code);
            })
        },
    })
}
const onDictTreeDelete = (data?: any) => {
    service.confirm(`确认删除字典分类：${data.fieldDesc}及其所有键值?`, {
        url: '/dict/tree',
        data: {combinationId: data.combinationId},
        success: ()=> onRefreshDictTree()
    })
}

//树点击事件
const onDictNodeClick = (value: any = dictTreeRef.value.getCurrentNode()) => {
    if (value) {
        dictLoading.value =true;
        dicItemParams.value.tableName = value['tableName']
        dicItemParams.value.fieldName = value['fieldName']
        dicItemParams.value.fieldDesc = value['fieldDesc']
        service.get('/dict', dicItemParams.value).then(({code, data}) => {
            dicts.value = code === 200? data.rows:[]
        }).finally(() => dictLoading.value = false)
    }
}


//添加
const onCreate = () => {
    const last = dicts.value.last();
    service.post('/dict', {...dicItemParams.value, order: (last?.order ?? 0) + 1}).then(({code}) => {
        code === 200 && onDictNodeClick();
    })
}

//编辑键值
const onEdit = (row: any, isEdit: boolean) => {
    currentEditRow.value = isEdit? {...row}:undefined;
    if (!isEdit) {
        service.put('/dict', row).then(({code}) => {
            code === 200 && onDictNodeClick();
        })
    }
}

//删除键值
const onDelete = (row: any) => {
    service.confirm(`确认删除字典：${row.description}?`, {
        url: '/dict',
        data: {dictIds: row.dictId},
        success: ()=> onDictNodeClick()
    })
}



onMounted(() => {
    onRefreshDictTree()
})
</script>

<style scoped>
.custom-tree-node {
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 20px;
    height: 100%;
}

.custom-tree-node .code {
    font-size: 12px;
    color: #999;
}

.custom-tree-node .status {
    font-size: 12px;
    color: #999;
}

.custom-tree-node .do {
    display: none;
}


.custom-tree-node .do > .el-button + .el-button {
    margin-left: 12px;
}

.custom-tree-node .do > .el-button.is-circle{
    width: auto;
}

.custom-tree-node .do > .el-button.is-link{
    padding: 0;
}

.custom-tree-node:hover .code {
    display: none;
}

.custom-tree-node:hover .status {
    display: none;
}

.custom-tree-node:hover .do {
    display: inline-block;
}

</style>